package com.ai_chat.sys.service.impl;

import com.ai_chat.sys.entity.Payment;
import com.ai_chat.sys.entity.TokenPackage;
import com.ai_chat.sys.entity.User;
import com.ai_chat.sys.mapper.PaymentMapper;
import com.ai_chat.sys.mapper.TokenPackageMapper;
import com.ai_chat.sys.mapper.UserMapper;
import com.ai_chat.sys.service.IPaymentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements IPaymentService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PaymentMapper paymentMapper;

    @Autowired
    private TokenPackageMapper tokenPackageMapper;

    public void payNotify(String userId, String price,Integer packageId,String payNo) {
        //处理price
        String[] strings=price.split("\\.");
        int priceNumber=Integer.parseInt(strings[0]+strings[1]);
        //创建订单
        Payment payment=new Payment();
        payment.setUserId(Integer.parseInt(userId));
        payment.setPrice(priceNumber);
        payment.setPackageId(packageId);
        payment.setPayNo(payNo);
        payment.setPayTime(LocalDateTime.now());

        paymentMapper.insert(payment);

        //更新token
        //查询套餐token数
        LambdaQueryWrapper<TokenPackage> condition = new LambdaQueryWrapper<>();
        condition.eq(TokenPackage::getId, packageId);
        TokenPackage tokenPackage =  tokenPackageMapper.selectOne(condition);
        //更新user的token值。
        User user= userMapper.selectById(userId);
        user.setToken(user.getToken() + tokenPackage.getPackageToken());
        userMapper.updateById(user);

    }

    public List<Payment> getPaymentList(Integer id){
        LambdaQueryWrapper<Payment> condition = new LambdaQueryWrapper<>();
        condition.eq(Payment::getUserId,id);

        //降序，新payment在上面
        condition.orderByDesc(Payment::getId);
        return paymentMapper.selectList(condition);
    }

    public void deletePayment(Payment payment){
        paymentMapper.deleteById(payment);

    }

}
